import os.path
import traceback
from typing import List

import allure
import yaml

from appium_xueqiu.until.log_until import logger


def join_path(catalogue, name):
    abspath = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), f'{catalogue}', f'{name}')

    return abspath


def black_handle(func):
    def _inner(*args, **kwargs):
        from appium_xueqiu.page_object.base_page.base_page import BasePage
        basepage: BasePage = args[0]

        try:
            logger.info(f"开始查找元素 ==> {args}")
            return func(*args, **kwargs)
        except Exception as e:
            logger.info(f"未找到元素，开始处理黑名单")
            cur_time = basepage.get_time()
            image_name = f"{cur_time}.png"
            img_path = join_path('images', image_name)
            logger.info(f"当前图片地址为：{img_path}")
            basepage.screenshot(img_path)
            allure.attach.file(img_path, name="黑名单查找", attachment_type=allure.attachment_type.PNG)
            for black in basepage.BLACK_LIST:
                logger.info(f"处理黑名单{black}")
                elements: List = basepage.do_finds(black)
                if len(elements) > 0:
                    elements[0].click()
                    return func(*args, **kwargs)
            logger.error(f"遍历黑名单，仍未找到对应元素， 异常信息 ===> {e}")
            logger.error(f"traceback.format_exc() ===> {traceback.format_exc()}")
            raise e

    return _inner


def get_data(filename):
    with open(join_path('data', filename), 'r', encoding='utf-8') as file:
        data = yaml.safe_load(file)

    return data


if __name__ == '__main__':
    imgage_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'images', '123.png')
    print(imgage_path)
